package test.lucene;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

public class LuceneUtil {
	
	static String path = DataImport.class.getResource("").getPath().split("target")[0] + "data";
	
	public static FSDirectory init() {
		try {
			return FSDirectory.open(Paths.get(new File(path).toURI()));
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public static void deleteAll() {
		IndexWriter writer = null;
		try {
			FSDirectory dir = FSDirectory.open(Paths.get(new File(path).toURI()));
			writer = new IndexWriter(dir, new IndexWriterConfig(new SimpleAnalyzer()));
			writer.deleteAll();
			writer.commit();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void getTop10() {
		try {
			FSDirectory dir = FSDirectory.open(Paths.get(new File(path).toURI()));
			DirectoryReader reader = DirectoryReader.open(dir);
			IndexSearcher searcher = new IndexSearcher(reader);
			TopDocs docs = searcher.search(new MatchAllDocsQuery(), 10);
			System.out.println("检索到" + docs.totalHits + "条记录");
			for(ScoreDoc doc : docs.scoreDocs) {
				Document document = searcher.doc(doc.doc);
				System.out.println(doc.score + "--->" + document.get("id"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
